package by.bsu.rfe.belianko.euniversity.controller.command;

import javax.servlet.http.HttpServletRequest;

import org.apache.log4j.Logger;

import by.bsu.rfe.belianko.euniversity.constants.ErrorMessages;
import by.bsu.rfe.belianko.euniversity.constants.LoggerMessages;
import by.bsu.rfe.belianko.euniversity.constants.PageNames;
import by.bsu.rfe.belianko.euniversity.dao.IStudentsDAO;
import by.bsu.rfe.belianko.euniversity.exceptions.CommandException;
import by.bsu.rfe.belianko.euniversity.exceptions.DaoTechnicalException;
import by.bsu.rfe.belianko.euniversity.model.DataBaseLayer;

/**
 * Approves the student on the faculty.
 * 
 * @author Vitali_Belianko
 * 
 */
public class ApproveCommand implements Command {
	private static final String CAN_NOT_APPROVE_STUDENTS = "Can not approve students!";
	private static final String APPROVE = "approve";
	private static final String NOT_APPROVED = "notApproved";
	private static final IStudentsDAO studentsDao = DataBaseLayer.getStudentsDao();
	private static final Logger LOGGER = Logger.getLogger(ApproveCommand.class);

	/**
	 * Approves students to the faculty by the marked checkbox.
	 * 
	 * @param request
	 * 
	 * @return admin page
	 * @throws CommandException
	 */
	@Override
	public String execute(HttpServletRequest request) throws CommandException {

		LOGGER.debug(LoggerMessages.STARTED_COMMAND);

		String[] approvedStudentList = request.getParameterValues(APPROVE);
		if(approvedStudentList!=null){
		int approvedStudentListLength = approvedStudentList.length;
		long[] idArray = new long[approvedStudentListLength];

		for (int i = 0; i < approvedStudentListLength; i++) {
			idArray[i] = Long.parseLong(approvedStudentList[i]);
		}

		try {
			studentsDao.approveStudents(idArray);
		} catch (DaoTechnicalException e) {
			LOGGER.error(e.getMessage());
			throw new CommandException(CAN_NOT_APPROVE_STUDENTS, e);
		}
		try {
			request.setAttribute(NOT_APPROVED, studentsDao.getNotApprovedStudents());
		} catch (DaoTechnicalException e) {
			LOGGER.error(e.getMessage());
			throw new CommandException(ErrorMessages.CAN_NOT_GET_NOT_APPROVED_STUDENTS, e);
		}
		}
		LOGGER.debug(LoggerMessages.FINISHED_COMMAND);

		return PageNames.ADMIN_PAGE;
	}

}
